package indi.lddsdu.index;


import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by jack on 18/6/18.
 * 原本的文件没有很好的去除空格，导致在检索使用highLighter的时候显示的效果不是很好
 */
public class FileFormatter {
    public static final String SOURCE_FOLDER = "/Users/jack/Desktop/htmlView";
    public static final String TARGET_FOLDER = "/Users/jack/Desktop/htmlView2";
    private static Pattern spacePattern = Pattern.compile("\\s{2,}", Pattern.CASE_INSENSITIVE);
    static {
        File file = new File(TARGET_FOLDER);
        if (!file.exists()){
            file.mkdir();
        }
    }

    /**
     * 将source文件的内容处理后写入到target中去
     * @param source
     * @param target
     */
    public static void deleteSpace(File source, File target) throws IOException {
        if (!source.exists()){
            throw new RuntimeException("文件"+ source + "不存在");
        }
        if (!target.exists()){
            target.createNewFile();
        }
        FileReader fileReader = new FileReader(source);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        StringBuffer sbin = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null){
            sbin.append(line);
        }
        bufferedReader.close();
        fileReader.close();
        String content = sbin.toString();
        content = deleteSpace(content);
        FileOutputStream fileOutputStream = new FileOutputStream(target);
        fileOutputStream.write(content.getBytes());
        fileOutputStream.close();
    }

    /**
     * 删除多余空格返回
     * @param content
     * @return
     */
    private static String deleteSpace(String content){
        Matcher matcher = spacePattern.matcher(content);
        content = matcher.replaceAll(" ");
        return content;
    }
}
